<template>
  <div>
    <a-drawer
      :open="props.open"
      title="详情"
      placement="right"
      @close="handleClose"
      width="800px"
    >
      <div class="flex justify-between">
        <a-form :label-col="labelCol" :disabled="isForm" :model="formSate">
          <a-form-item label="子公司">
            <a-input
              style="width: 200px"
              disabled
              v-model:value="formSate.comNameLevel5"
            />
          </a-form-item>
          <a-form-item label="换热站">
            <template v-if="!isEdit && !isForm">
              <a-checkbox
                v-model:checked="selectedFields.heatExchangeStationName"
                class="mr-2"
              ></a-checkbox>
            </template>
            <a-input
              style="width: 200px"
              v-model:value="formSate.heatExchangeStationName"
            />
          </a-form-item>
          <a-form-item label="站级">
            <template v-if="!isEdit && !isForm">
              <a-checkbox
                v-model:checked="selectedFields.stationLevel"
                class="mr-2"
              ></a-checkbox>
            </template>
            <a-input
              style="width: 200px"
              v-model:value="formSate.stationLevel"
            />
          </a-form-item>
          <a-form-item label="可研名称">
            <template v-if="!isEdit && !isForm">
              <a-checkbox
                v-model:checked="selectedFields.feasibilityStudyName"
                class="mr-2"
              ></a-checkbox>
            </template>
            <a-input
              style="width: 200px"
              v-model:value="formSate.feasibilityStudyName"
            />
          </a-form-item>
          <a-form-item label="设计能力">
            <template v-if="!isEdit && !isForm">
              <a-checkbox
                v-model:checked="selectedFields.designAbility"
                class="mr-2"
              ></a-checkbox>
            </template>
            <a-input
              style="width: 200px"
              v-model:value="formSate.designAbility"
            />
          </a-form-item>
          <a-form-item label="建设管网长度">
            <template v-if="!isEdit && !isForm">
              <a-checkbox
                v-model:checked="selectedFields.designPipelineLength"
                class="mr-2"
              ></a-checkbox>
            </template>
            <a-input
              style="width: 200px"
              v-model:value="formSate.designPipelineLength"
            />
          </a-form-item>
          <a-form-item label="完全能力">
            <template v-if="!isEdit && !isForm">
              <a-checkbox
                v-model:checked="selectedFields.completeAbility"
                class="mr-2"
              ></a-checkbox>
            </template>
            <a-input
              style="width: 200px"
              v-model:value="formSate.completeAbility"
            />
          </a-form-item>
          <a-form-item label="用电性质">
            <template v-if="!isEdit && !isForm">
              <a-checkbox
                v-model:checked="selectedFields.electricType"
                class="mr-2"
              ></a-checkbox>
            </template>
            <a-input
              style="width: 200px"
              v-model:value="formSate.electricType"
            />
          </a-form-item>
          <a-form-item label="用水性质">
            <template v-if="!isEdit && !isForm">
              <a-checkbox
                v-model:checked="selectedFields.waterType"
                class="mr-2"
              ></a-checkbox>
            </template>
            <a-input style="width: 200px" v-model:value="formSate.waterType" />
          </a-form-item>
          <a-form-item label="用气性质">
            <template v-if="!isEdit && !isForm">
              <a-checkbox
                v-model:checked="selectedFields.gasType"
                class="mr-2"
              ></a-checkbox>
            </template>
            <a-input style="width: 200px" v-model:value="formSate.gasType" />
          </a-form-item>
          <a-form-item label="热源类型">
            <template v-if="!isEdit && !isForm">
              <a-checkbox
                v-model:checked="selectedFields.heatSourceType"
                class="mr-2"
              ></a-checkbox>
            </template>
            <a-input
              style="width: 200px"
              v-model:value="formSate.heatSourceType"
            />
          </a-form-item>
        </a-form>
        <a-form :label-col="labelCol" :disabled="isForm" :model="formSate">
          <a-form-item label="热源站">
            <template v-if="!isEdit && !isForm">
              <a-checkbox
                v-model:checked="selectedFields.heatSourceName"
                class="mr-2"
              ></a-checkbox>
            </template>
            <a-input
              style="width: 200px"
              v-model:value="formSate.heatSourceName"
            />
          </a-form-item>
          <a-form-item label="换热站名称(财务)">
            <template v-if="!isEdit && !isForm">
              <a-checkbox
                v-model:checked="selectedFields.heatExchangeStationNameACC"
                class="mr-2"
              ></a-checkbox>
            </template>
            <a-input
              style="width: 200px"
              v-model:value="formSate.heatExchangeStationNameACC"
            />
          </a-form-item>
          <a-form-item label="换热站编号">
            <template v-if="!isEdit && !isForm">
              <a-checkbox
                v-model:checked="selectedFields.heatExchangeStationNumber"
                class="mr-2"
              ></a-checkbox>
            </template>
            <a-input
              style="width: 200px"
              v-model:value="formSate.heatExchangeStationNumber"
            />
          </a-form-item>
          <a-form-item label="可研编号">
            <template v-if="!isEdit && !isForm">
              <a-checkbox
                v-model:checked="selectedFields.feasibilityStudyNumber"
                class="mr-2"
              ></a-checkbox>
            </template>
            <a-input
              style="width: 200px"
              v-model:value="formSate.feasibilityStudyNumber"
            />
          </a-form-item>
          <a-form-item label="不完全能力">
            <template v-if="!isEdit && !isForm">
              <a-checkbox
                v-model:checked="selectedFields.incompleteAbility"
                class="mr-2"
              ></a-checkbox>
            </template>
            <a-input
              style="width: 200px"
              v-model:value="formSate.incompleteAbility"
            />
          </a-form-item>
          <a-form-item label="签约面积">
            <template v-if="!isEdit && !isForm">
              <a-checkbox
                v-model:checked="selectedFields.contractedArea"
                class="mr-2"
              ></a-checkbox>
            </template>
            <a-input
              style="width: 200px"
              v-model:value="formSate.contractedArea"
            />
          </a-form-item>
          <a-form-item label="建筑形式">
            <template v-if="!isEdit && !isForm">
              <a-checkbox
                v-model:checked="selectedFields.buildingType"
                class="mr-2"
              ></a-checkbox>
            </template>
            <a-input
              style="width: 200px"
              v-model:value="formSate.buildingType"
            />
          </a-form-item>
          <a-form-item label="用电单价(元/度)">
            <template v-if="!isEdit && !isForm">
              <a-checkbox
                v-model:checked="selectedFields.electricPrice"
                class="mr-2"
              ></a-checkbox>
            </template>
            <a-input
              style="width: 200px"
              v-model:value="formSate.electricPrice"
            />
          </a-form-item>
          <a-form-item label="用水单价(元/m³)">
            <template v-if="!isEdit && !isForm">
              <a-checkbox
                v-model:checked="selectedFields.waterPrice"
                class="mr-2"
              ></a-checkbox>
            </template>
            <a-input style="width: 200px" v-model:value="formSate.waterPrice" />
          </a-form-item>
          <a-form-item label="用气单价(元/m³)">
            <template v-if="!isEdit && !isForm">
              <a-checkbox
                v-model:checked="selectedFields.gasPrice"
                class="mr-2"
              ></a-checkbox>
            </template>
            <a-input style="width: 200px" v-model:value="formSate.gasPrice" />
          </a-form-item>
          <a-form-item label="投产时间">
            <template v-if="!isEdit && !isForm">
              <a-checkbox
                v-model:checked="selectedFields.createdTime"
                class="mr-2"
              ></a-checkbox>
            </template>
            <a-input
              style="width: 200px"
              v-model:value="formSate.createdTime"
            />
          </a-form-item>
        </a-form>
      </div>
      <div class="text-right">
        <a-button
          type="primary"
          :icon="h(ScheduleFilled)"
          @click="handleChangeRecord"
          >换热站信息修改记录</a-button
        >
      </div>
      <template #footer v-if="isForm">
        <a-space>
          <a-button
            type="primary"
            :icon="h(EditFilled)"
            @click="
              () => {
                isEdit = true;
                isForm = false;
                resetSelectedFields();
              }
            "
            v-if="props.auth.updates == 1"
            >修改</a-button
          >
          <a-button
            type="primary"
            :icon="h(EditFilled)"
            @click="
              () => {
                isEdit = false;
                isForm = false;
                resetSelectedFields();
              }
            "
            v-if="props.auth.updates == 1"
            >批量修改</a-button
          >
        </a-space>
      </template>
      <template #footer v-if="!isForm">
        <a-space>
          <a-button type="primary" @click="onsubmit">提交</a-button>
          <a-button
            @click="
              () => {
                isForm = true;
                handleClose();
              }
            "
            >取消</a-button
          >
        </a-space>
      </template>
      <a-modal
        :visible="changeRecord"
        title="修改记录"
        :footer="null"
        width="1200px"
        @cancel="changeRecord = false"
      >
        <a-table
          :columns="columns"
          :data-source="changeRecordData"
          :pagination="pagination"
        />
      </a-modal>
    </a-drawer>
  </div>
</template>
<script setup lang="ts">
import { ref, h, watch, reactive } from 'vue';
import { ScheduleFilled, EditFilled } from '@ant-design/icons-vue';
import {
  updateHeatStation,
  getHeatExchangeStationBatchOperation_four,
  getHeatExchangeStationChangeRecordApi,
} from '#/api';
import { message } from 'ant-design-vue';
interface Props {
  selectedType: string;
  data: any;
  open: boolean;
  auth: Record<string, any>;
}

const props = defineProps<Props>();
const formSate = ref<Record<string, any>>({});

const isEdit = ref(false);
const labelCol = { style: { width: '120px' } };
const isForm = ref(true);
const changeRecordData = ref<any[]>([]);
const emit = defineEmits(['handleClose', 'refreshData']);
const handleClose = () => {
  emit('handleClose');
};
const changeRecord = ref(false);
const columns = [
  {
    title: '子公司',
    dataIndex: 'comNameLevel5',
    align: 'center',
  },
  {
    title: '区域',
    dataIndex: 'comNameLevel4',
    align: 'center',
  },
  {
    title: '热源站',
    dataIndex: 'heatSourceName',
    align: 'center',
  },
  {
    title: '换热站',
    dataIndex: 'heatExchangeStationName',
    align: 'center',
  },
  {
    title: '换热站名称(财务)',
    dataIndex: 'heatExchangeStationNameACC',
    align: 'center',
  },
  {
    title: '站级',
    dataIndex: 'stationLevel',
    align: 'center',
  },
  {
    title: '建筑形式',
    dataIndex: 'buildingType',
    align: 'center',
  },
  {
    title: '换热站编号',
    dataIndex: 'heatExchangeStationNumber',
    align: 'center',
  },
  {
    title: '热源形式',
    dataIndex: 'heatSourceType',
    align: 'center',
  },
  {
    title: '是否完成',
    dataIndex: 'isCompleted',
    key: 'isCompleted',
  },
  {
    title: '操作类型',
    dataIndex: 'operType',
    key: 'operType',
  },
  {
    title: '操作人',
    dataIndex: 'reporter',
    key: 'reporter',
  },
  {
    title: '操作时间',
    dataIndex: 'operTime',
    key: 'operTime',
  },
];
const pagination = reactive({
  total: 0,
  pageSize: 10,
  current: 1,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条`,
  onChange: (page: number, pageSize: number) => {
    pagination.current = page;
    pagination.pageSize = pageSize;
    getHeatExchangeStationChangeRecordApi({
      page: page,
      limit: pageSize,
      heatExchangeStationID: props.data.heatExchangeStationId,
    }).then((res) => {
      // console.log('res', res);
      changeRecordData.value = res.data.data;
      pagination.total = res.data.count;
    });
  },
});
// 用于存储批量编辑时选中的字段
const selectedFields = reactive({
  comNameLevel5: false,
  heatExchangeStationName: false,
  stationLevel: false,
  feasibilityStudyName: false,
  designAbility: false,
  designPipelineLength: false,
  completeAbility: false,
  electricType: false,
  waterType: false,
  gasType: false,
  heatSourceType: false,
  heatSourceName: false,
  heatExchangeStationNameACC: false,
  heatExchangeStationNumber: false,
  feasibilityStudyNumber: false,
  incompleteAbility: false,
  contractedArea: false,
  buildingType: false,
  electricPrice: false,
  waterPrice: false,
  gasPrice: false,
  createdTime: false,
});

// 重置选中的字段
const resetSelectedFields = () => {
  Object.keys(selectedFields).forEach((key) => {
    selectedFields[key] = false;
  });
};

watch(
  () => props.data,
  (newVal) => {
    console.log('newVal', newVal);
    // 确保newVal是一个数组，并且长度大于0，然后将其赋值给formSate.value
    if (newVal) {
      formSate.value = { ...newVal };
    }
  },
);
const onsubmit = () => {
  if (isEdit.value) {
    const data = {
      ...formSate.value,
      regionId: props.data.regionId,
      applicationReason: props.data.applicationReason,
      attachmentLocation: props.data.attachmentLocation,
      operateObject: props.data.operateObject,
    };
    // 单独修改逻辑
    updateHeatStation(data).then((res) => {
      console.log('单独修改', res);
      if (res === '修改成功!') {
        message.success(res);
        isForm.value = true;
        emit('refreshData'); // 通知父组件刷新数据
        handleClose();
      } else {
        message.error(res || '修改失败!');
      }
    });
  } else {
    // 批量修改逻辑
    // 创建一个只包含选中字段的对象
    const selectedData = {};
    Object.keys(selectedFields).forEach((key) => {
      if (selectedFields[key]) {
        selectedData[key] = formSate.value[key];
      }
    });

    // 检查是否有选中的字段
    if (Object.keys(selectedData).length === 0) {
      message.warning('请至少选择一个要修改的字段');
      return;
    }

    // 这里需要实现批量修改的API调用
    console.log('批量修改的数据', selectedData);
    const data = {
      ...selectedData,
      regionId: props.data.regionId,
      applicationReason: props.data.applicationReason,
      attachmentLocation: props.data.attachmentLocation,
      operateObject: props.data.operateObject,
    };
    // 示例：调用批量修改API
    getHeatExchangeStationBatchOperation_four(data).then((res) => {
      if (res.data.code === 200) {
        message.success('批量修改成功!');
        isForm.value = true;
        emit('refreshData'); // 通知父组件刷新数据
        handleClose();
      } else {
        message.error(res.message || '批量修改失败!');
      }
    });

    // 临时提示，实际项目中应替换为真实API调用
    // message.success('批量修改功能已触发，请实现对应的API');
    // isForm.value = true;
    // handleClose();
  }
};
const handleChangeRecord = () => {
  changeRecord.value = true;
  getHeatExchangeStationChangeRecordApi({
    page: pagination.current,
    limit: pagination.pageSize,
    heatExchangeStationID: props.data.heatExchangeStationId,
  }).then((res) => {
    // console.log('res', res);
    changeRecordData.value = res.data.data;
    pagination.total = res.data.count;
  });
};
</script>
<style scoped>
.mr-2 {
  margin-right: 8px;
}
</style>
